package com.benshou.bcss.common.quartz;

import lombok.RequiredArgsConstructor;
import org.quartz.Scheduler;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * JobKey 巡检
 * <p>
 *     用于在 Spring Bean 准备完成后，进行检查性测试。例如检查是否与持久化数据强一致。
 * </p>
 *
 * @author <a href="mailto:liuzhenbang@benshou.com">Liu Zhenbang</a>
 */
@Component
@RequiredArgsConstructor
public class JobKeyInspection implements ApplicationRunner {

    /**
     * JobKey 注册器
     */
    private final JobKeyRegister jobKeyRegister;

    /**
     * 任务调度实例
     */
    private final Scheduler scheduler;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // FIXME 根据 JobKey 判断只是第一步，还需要根据 JobDetail 与 Trigger 进行实际判断
        for (var jobKey : this.scheduler.getJobKeys(GroupMatcher.anyGroup())) {
            if (!this.jobKeyRegister.contains(jobKey)) {
                this.scheduler.deleteJob(jobKey);
            }
        }
    }
}
